﻿Imports System.IO
Imports System.Text.RegularExpressions

Public Class utils

    'Create the sitemapindex for a given folder
    Public Shared Sub WriteSiteMapIndex(ByVal strSourceFolder As String, ByVal strFileName As String)
        Dim swi As StreamWriter
        File.Delete(strSourceFolder & "/" & strFileName & "Index.xml")
        FileCreate(strFileName)
        swi = File.AppendText(strSourceFolder & "/" & strFileName & "Index.xml")
        swi.WriteLine("<?xml version=""1.0"" encoding=""UTF-8""?>")
        swi.WriteLine("<sitemapindex xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"">")

        'Add Existing files
        Dim dirinfo As DirectoryInfo = New DirectoryInfo(strSourceFolder)
        Dim allFiles() As FileInfo = dirinfo.GetFiles("*.xml")
        Array.Sort(allFiles, New clsCompareFileInfo)
        For Each myFile As FileInfo In allFiles
            If Not myFile.Name.Contains("Index") Then
                swi.WriteLine("<sitemap>")
                swi.WriteLine("<loc>http://www.remax.com/sitemaps/" & myFile.Name & "</loc>")
                swi.WriteLine("<lastmod>" & DatePart("yyyy", myFile.LastWriteTime) & _
                              "-" & DatePart("m", myFile.LastWriteTime).ToString().PadLeft(2, "0") & _
                              "-" & DatePart("d", myFile.LastWriteTime).ToString().PadLeft(2, "0") & "</lastmod>")
                swi.WriteLine("</sitemap>")
            End If
        Next

        swi.WriteLine("</sitemapindex>")
        swi.Flush()
        swi.Close()
    End Sub


    'Create a new file
    Public Shared Sub FileCreate(ByVal Path As String)
        Dim fs As FileStream = File.Create(Path)
        fs.Close()
    End Sub


    'Move files from one directory to another
    Public Shared Sub MoveFiles(ByVal strSourceFolder As String, ByVal strFinalFolder As String)
        For Each myFile In Directory.GetFiles(strSourceFolder, "*.xml")
            Call File.Move(myFile, strFinalFolder & "\" & Path.GetFileName(myFile))
            If File.Exists(myFile) Then
                File.Delete(myFile)
            End If
        Next
    End Sub


    'Get the latest processed file
    Public Shared Function getLatestFile(ByVal strFolderToCheck As String, ByVal strFileName As String) As Integer
        Dim intFileNum As Integer = 0
        If Directory.Exists(strFolderToCheck) Then
            Dim strTemp As String
            Dim intTemp As Integer
            For Each myFile In Directory.GetFiles(strFolderToCheck, "*.xml")
                strTemp = Path.GetFileName(myFile)
                strTemp = Strings.Replace(strTemp, ".xml", "", 1, -1, CompareMethod.Text)
                strTemp = Strings.Replace(strTemp, strFileName, "", 1, -1, CompareMethod.Text)
                If IsNumeric(strTemp) Then
                    intTemp = CInt(strTemp)
                    If intTemp >= intFileNum Then
                        intFileNum = intTemp + 1
                    End If
                End If
            Next
        Else
            Directory.CreateDirectory(strFolderToCheck)
        End If
        Return intFileNum
    End Function


    'Checks to make sure the folder is there for the files to be save into.
    Public Shared Sub CheckFolderStatus(ByVal strFolderToCheck As String, ByVal isDelta As Boolean)
        If Directory.Exists(strFolderToCheck) Then
            If Not isDelta Then
                Directory.Delete(strFolderToCheck, True)
                Directory.CreateDirectory(strFolderToCheck)
            End If
        Else
            Directory.CreateDirectory(strFolderToCheck)
        End If
    End Sub


    'Writes the header for the file for the.
    Public Shared Sub WriteFileHeader(ByVal MyFile)
        MyFile.WriteLine("<?xml version=""1.0"" encoding=""UTF-8""?>")
        MyFile.WriteLine("<urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"">")
    End Sub


    'Either creates file or opens previous file.
    Public Shared Sub AppendtoFile(ByVal sw As StreamWriter, ByVal strLine As String, ByVal count As Integer, ByVal strFolder As String, ByVal Filename As String)
        Dim strFileName As String = strFolder & "\" & Filename & count & ".xml"
        If sw Is Nothing Then
            If File.Exists(strFileName) Then
                sw = File.AppendText(strFileName)
            Else
                FileCreate(strFileName)
                sw = File.AppendText(strFileName)
                Call WriteFileHeader(sw)
            End If
        End If
        sw.WriteLine(strLine)
    End Sub


    'Replace some strings from a url
    Public Shared Function CleanURLString(ByVal str As String) As String
        If str <> String.Empty Then
            Dim regexps As List(Of Regex) = New List(Of Regex)
            Dim replacements As List(Of String) = New List(Of String)

            regexps.Add(New Regex("&(.{1,4});")) ' this will match all the words like &sbnp; &gt; &#123;
            replacements.Add("")

            regexps.Add(New Regex("[#]"))
            replacements.Add("-no-")

            regexps.Add(New Regex("[@]"))
            replacements.Add("-at-")

            regexps.Add(New Regex("\s+"))
            replacements.Add("-")

            regexps.Add(New Regex("[^A-Za-z0-9_-]")) ' this will match all the Non words except _ and -
            replacements.Add("")

            regexps.Add(New Regex("(_+)")) ' this will match all the repeated _ and replace for just one _
            replacements.Add("-")

            regexps.Add(New Regex("(-+)")) ' this will match all the repeated - and replace for just one -
            replacements.Add("-")

            regexps.Add(New Regex("(-_|_-)")) ' this will match all the _-  or -_ and replace for  -
            replacements.Add("-")

            regexps.Add(New Regex("([^A-Za-z0-9])+$")) ' this will match all the Non Words at the end of the string
            replacements.Add("")

            regexps.Add(New Regex("(_[gG][eE][tT])")) ' match if the word _get exists
            replacements.Add("_G_et")

            regexps.Add(New Regex("(_[pP][oO][sS][tT])")) ' match if the word _post exists
            replacements.Add("_P_ost")

            regexps.Add(New Regex("(_[cC][oO][oO][kK][iI][eE][sS])")) ' match if the word _cookies exists
            replacements.Add("_C_ookies")

            regexps.Add(New Regex("(_[fF][iI][lL][eE][sS])")) ' match if the word _files exists
            replacements.Add("_F_iles")

            regexps.Add(New Regex("(_[sS][eE][rR][vV][eE][rR])")) ' match if the word _server exists
            replacements.Add("_S_erver")

            regexps.Add(New Regex("(_[eE][nN][vV])")) ' match if the word _env exists
            replacements.Add("_E_nv")

            regexps.Add(New Regex("(_[gG][lL][oO][bB][aA][lL][sS])")) ' match if the word _globals exists
            replacements.Add("_G_lobals")

            regexps.Add(New Regex("(_[sS][eE][sS][sS][iI][oO][nN])")) ' match if the word _session exists
            replacements.Add("_S_ession")

            Dim i As Integer = 0
            For Each regexp As Regex In regexps
                str = regexp.Replace(str, replacements.Item(i))
                i += 1
            Next

        End If
        Return str.ToLower()
    End Function




End Class

Public Class clsCompareFileInfo
    Implements IComparer
    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
        Dim File1 As FileInfo = DirectCast(x, FileInfo)
        Dim File2 As FileInfo = DirectCast(y, FileInfo)
        Compare = DateTime.Compare(File1.LastWriteTime, File2.LastWriteTime)
    End Function
End Class